// component/com-im-overview/com-im-overview.js
import TIM from "../../utils/imLibs/tim-wx.js";
import { userInfoBehavior } from "../../behaviors/userInfo";
import p from "../../utils/platform.js";
import api from "../../common/api.js";
const { isReleaseUrl, envVersion } = require("../../utils/util");

const computedBehavior = require("miniprogram-computed");
const app = getApp();
let _this;
let sessionSubscriber;
Component({
  behaviors: [computedBehavior, userInfoBehavior],

  /**
   * 组件的属性列表
   */
  properties: {
    tabConentIndex: {
      type: Number,
      value: 0,
    },
    targetUnionId: String, //通过公众号消息 直接进入与好友的聊天页
  },

  options: {
    styleIsolation: "apply-shared",
    addGlobalClass: true,
  },

  /**
   * 组件的初始数据
   */
  data: {
    name: "com-im-overview",
    userID: "",
    tabList: [
      { id: "joinHands", label: "合作咨询", add: "" },
      // { id: "customer", label: "客户咨询", add: "" },
      // { id: "system", label: "系统消息", add: "" },
    ],
    tabSelect: "joinHands",
    conversationList: [], //会话列表
    systemMessageList: [1],
    list: [],
    isWaitComeBack: false, //是否是回来
    isLoading: true,
    alreadyImInit: false, //记录是否初始化过
    ignoreTarget: false,
  },

  observers: {
    tabConentIndex() {
      if (this.data.tabConentIndex != 2) return;

      this.initIm();
    },
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function () {
      _this = this;

      // 用户资料更新时需要同步更新到im
      sessionSubscriber = this.updateMyProfile.bind(this);
      app && app.eventBus && app.eventBus.on("update_sessionuser", sessionSubscriber);
    },
    moved: function () {},
    detached: function () {
      app && app.eventBus && app.eventBus.off("update_sessionuser", sessionSubscriber);
    },
  },

  pageLifetimes: {
    show: function () {
      if (!this.data.alreadyImInit) {
        if (!isReleaseUrl && envVersion == "develop" && !app.globalData.imStart) return;
      }

      this.initIm();
    },
    hide: function () {
      this.removeEvent();
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initIm() {
      this.data.alreadyImInit = true;
      app.globalData.loginPromise.then((content) => {
        if (!app.timControl.sdkReady) {
          // 此处需要考虑新用户暂时未授权信息
          let unionid = content.sessionUser.extProps.wechatUnionid;
          if (!unionid) return console.error("新用户尚未授权基本信息");
          this.setData({ userID: unionid });

          this.addEvent();
          app.timControl.login(unionid);
        } else {
          this.addEvent();
          this.getConversationList();
        }
      });
    },

    // 通过公众号直接进来聊天，需要记录来自公众号认证消息，or 公众号普通消息
    getPageFrom() {
      const value = app.globalData.pageFrom
      if (value) {
        app.globalData.pageFrom = ''
        return value
      }
      return '消息页'
    },

    // im准备就绪
    onSdkReady() {
      _this.updateMyProfile().then(() => {
        _this.setData({ isLoading: false });
      });
    },

    handleGoChat(e) {
      app.timControl.sdkReadyAndNext(this.data.userID).then(() => {
        let id = e.currentTarget.dataset.conversationid;
        let userid = e.currentTarget.dataset.userid;
        p.navigateTo({ url: `/pages/im/imMessagelist/imMessagelist?conversationid=${id}&unionid=${userid}&pageFrom=${this.getPageFrom()}`});
      });
    },

    // 监听列表更新
    onListUpdatedHandler(e) {
      _this.conversationHandler(e.data);
    },

    // 对会话列表数据统一处理
    conversationHandler(csList) {
      if (!Array.isArray(csList)) return;

      const cb = (csList) => {
        this.data.conversationList = csList;
        this.renderConversationList(csList);
        this.updateReadState(csList);
      };

      if (this.data.conversationList.length !== csList.length) {
        const cacheMap = csList.reduce((res, item) => {
          res[item.userProfile.userID] = item;
          return res;
        }, {});
        const ids = csList.map((v) => v.userProfile.userID);
        app.timControl.getUserProfile(ids).then((res) => {
          if (Array.isArray(res)) {
            res.forEach((item) => {
              if (item.profileCustomField) {
                cacheMap[item.userID].profileCustomField = item.profileCustomField;
              }
            });
          }
          cb(csList);
        });
      } else {
        cb(csList);
      }
    },

    // 获取会话列表
    getConversationList() {
      return app.timControl
        .getConversationList()
        .then((imResponse) => {
          let csList = imResponse.data.conversationList; // 会话列表，用该.列表覆盖原有的会话列表
          // console.log("%c 获取会话列表getConversationList", "color: red", csList);
          this.conversationHandler(csList);
          return Promise.resolve(csList);
        })
        .catch((err) => {
          console.warn("getConversationList error:", err); // 获取会话列表失败的相关信息
        });
    },

    // 修改个人标配资料
    updateMyProfile() {
      if (!app.timControl) return Promise.reject();
      return this.getAuthenticatedInfoByUnionid(this.data.userID).then((profile) => {
        if (!profile.nick || !profile.avatar) return;
        let p = app.timControl.updateMyProfile({
          nick: profile.nick,
          avatar: profile.avatar,
          allowType: TIM.TYPES.ALLOW_TYPE_ALLOW_ANY,
          profileCustomField: [
            {
              key: "Tag_Profile_Custom_authed",
              value: profile.isVerified ? "1" : "0",
            },
          ],
        });
        if (!p) return Promise.reject();
        return p.then(({ data }) => {
          // console.log("%c 更新资料成功", "color: red", data);
        });
      });
    },

    // 渲染合作咨询的聊天列表
    renderConversationList(data) {
      if (this.data.tabSelect == "joinHands") {
        _this.setData({ list: [...data] });

        if (this.data.targetUnionId && !this.data.ignoreTarget) {
          this.data.ignoreTarget = true
          p.navigateTo({
            url: `/pages/im/imMessagelist/imMessagelist?unionid=${this.data.targetUnionId}&pageFrom=${this.getPageFrom()}`,
          });
        }
      }
    },

    // tab切换
    tabnavIndexChange(e) {
      let id = e.detail.id;
      let list;
      switch (id) {
        case "joinHands":
          list = [...this.data.conversationList];
          this.setData({
            tabSelect: id,
            list,
          });
          break;
        case "customer":
          list = [];
          break;
        case "system":
          api.getSystemMessagePage(
            {
              pageNum: 1,
              pageSize: 99,
            },
            ({ data }) => {
              list = data.content.list;
              this.setData({
                tabSelect: id,
                list,
              });
            }
          );

          break;
      }
    },

    updateReadState(list) {
      let count = list.reduce((res, item) => res + item.unreadCount, 0);
      this.triggerEvent("onreadmsg", count);
    },

    handleMove() {
      this.triggerEvent("ontabchange", "合作");
    },

    addEvent() {
      app && app.timControl && app.timControl.eventBus.on(TIM.EVENT.SDK_READY, this.onSdkReady);
      app && app.timControl && app.timControl.eventBus.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onListUpdatedHandler);
    },
    removeEvent() {
      app && app.timControl && app.timControl.eventBus.off(TIM.EVENT.SDK_READY, this.onSdkReady);
      app && app.timControl && app.timControl.eventBus.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onListUpdatedHandler);
    },

    handleLoadMore() {},
  },
});
